<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/28
 * Time: 10:01
 */
namespace Admin\Controller;
use Admin\Controller\CommonController;

class StateController extends CommonController{
    public function index(){
        $state=M("country")->order("ename")->where("pid=0")->select();
        $this->assign("state",$state);
        $this->display();
    }
    public function add(){
        if(!IS_POST) {
            $state =$this->dg(M("country")->order("`order` DESC")->select());
            $this->assign("pid",I('get.pid'));
            $this->assign("state",$state);
            $this->display();
        }else{
            $data=I("post.");
            $arr['cname'] =$data['cname'];
            $arr['ename']=$data['ename'];
            $sele =M("country")->where($arr)->select();
            if($sele){
                $this->error("数据已存在");
            }else{
                $test=M("country")->data($data)->add();
                if($test) {
                    $this->success('操作成功！',__MODULE__.'/state/index');
                } else {
                    $this->error('操作失败！',__MODULE__.'/state/index');
                }
            }

        }

    }
    public function edit(){
        if(IS_POST) {
            $id=$_GET['nid'];
            if(empty($id)) {
                $this->error('异常操作！',__MODULE__.'/state/index');
            }else{
                $data=I("post.");
                $test=M("country")->data($data)->where("id={$id}")->save();
                if($test) {
                    $this->success('操作成功！',__MODULE__.'/state/index');
                } else {
                    $this->display("Public:error");
                }

            }
        }else{
            $id=$_GET["nid"];
            if(empty($id)) {
                $this->error('异常操作！',__MODULE__.'/state/index');
            }else{
                $arr=M("country")->where("id={$id}")->select();

                $this->assign("arr",$arr);
                $this->display();

            }
        }
    }
    public function del(){
        $nid = intval($_GET['nid']);
        if(empty($nid)) {
            $this->error('异常操作！',__MODULE__.'/state/index');
        }
        if(M("country")->where("id = {$nid}")->delete() !== fasle) {
            $this->success('操作成功！',__MODULE__.'/state/index');
        } else {
            $this->error('操作失败！',__MODULE__.'/state/index');
        }
    }
    public function dg($data,$pid=0,$empty="&nbsp;&nbsp;"){
        $arr = [];
        foreach($data as $val){
            if($val['pid']==$pid){
                $val['cname']=$empty.$val['cname'];
                $arr[]=$val;
                foreach($this->dg($data,$val['id'],$empty."|--&nbsp;&nbsp;")as $v){
                    $arr[]=$v;
                }
            }
        }
        return $arr;
    }
    public function _empty(){
        $this->error("404");
    }
}